package com.epalmpay.service.order.impl;

import com.alibaba.fastjson.JSON;
import com.epalmpay.dto.mall.EntityGoodInDTO;
import com.epalmpay.dto.order.*;
import com.epalmpay.entity.*;
import com.epalmpay.entity.Response;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.payplat.IPayAPI;
import com.epalmpay.payplat.TkRefund;
import com.epalmpay.payplat.UnPayConsumption;
import com.epalmpay.payplat.result.PayResult;
import com.epalmpay.payplat.result.RefundResult;
import com.epalmpay.service.app.IAppNoticeService;
import com.epalmpay.service.member.IMemberService;
import com.epalmpay.service.order.IOrderService;
import com.epalmpay.service.posapi.PosApiService;
import com.epalmpay.service.posapi.PosApiServiceTransactional;
import com.epalmpay.service.weixin.IWalletService;
import com.epalmpay.status.Rescode;
import com.epalmpay.dto.system.BaseOutDTO;
import com.epalmpay.enumdef.ActivityEnum;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.mapper.*;
import com.epalmpay.service.management.ITemplateMailSendService;
import com.epalmpay.service.order.IOrderGoodService;
import com.epalmpay.util.*;
import com.epalmpay.util.payplat.DateUtils;
import com.epalmpay.util.payplat.UtilFun;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Clock;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lifayi on 2017/9/2.
 */
@Service
public class OrderGoodServiceImpl implements IOrderGoodService {
    @Autowired
    private OrderGoodMapper orderGoodMapper;
    @Autowired
    private OrderGoodItemMapper orderGoodItemMapper;
    @Resource
    private MallEntityGoodMapper mallEntityGoodMapper;
    @Resource
    private MallEntityGoodSpecMapper mallEntityGoodSpecMapper;
    @Resource
    private CouponUserMapper couponUserMapper;
    @Resource
    private BonusVerifyLogMapper bonusVerifyLogMapper;
    @Resource
    private MemberMapper memberMapper;
    @Resource
    private MemberAddressMapper memberAddressMapper;
    @Resource
    private TradeOfflineMapper tradeOfflineMapper;
    @Resource
    private ShopGroupRelationMapper shopGroupRelationMapper;
    @Resource
    private GroupMapper groupMapper;
    @Resource
    private ShopMapper shopMapper;
    @Resource
    @Lazy
	private ITemplateMailSendService templateMailSendService;
    @Resource
    private PosApiServiceTransactional posApiServiceTransactional;
    @Resource
    private PosApiService posApiService;
    
    @Resource
	private StatisMemberMapper statisMemberMapper;
    
    //@Resource
    //private ServiceGoodController serviceGoodController;
    @Resource
    private IOrderService orderService;

    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    @Resource
    private IWalletService walletService;

    @Resource
    private IAppNoticeService appNoticeService;

    @Resource
    private IMemberService  memberService;


    protected Logger logger = Logger.getLogger(this.getClass());


    //@Resource(name="transactionManager")
    //private DataSourceTransactionManager transactionManager;

    @Override
    public List<OrderGoodOutDTO> listMallOrder(MallOrderQueryDTO mallOrderQueryDTO, Page page) throws ParseException {
        OrderGood orderGood = new OrderGood();
        orderGood.setPage(page);
        orderGood.setGroupId(mallOrderQueryDTO.getGroupId());
        orderGood.setOrderNo(mallOrderQueryDTO.getOrderNumOrPhone());
        orderGood.setStatus(mallOrderQueryDTO.getStatus());
        orderGood.setShopId(mallOrderQueryDTO.getShopId());

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStart = mallOrderQueryDTO.getDateStart();
        String dateEnd = mallOrderQueryDTO.getDateEnd();
        if(!Tools.isEmpty(dateStart)) {
            Date dateStartDate = dateFormat.parse(dateStart);
            orderGood.setDateStart(dateStartDate);
        }
        if(!Tools.isEmpty(dateEnd)) {
            Date dateEndDate = dateFormat.parse(dateEnd);
            orderGood.setDateEnd(DateUtil.getDateNext(dateEndDate, 1));
        }

        List<OrderGoodOutDTO> orderGoodOutDTOList = orderGoodMapper.listPageOrderGood(orderGood);
        for(int i = 0; i < orderGoodOutDTOList.size(); i++) {
            OrderGoodOutDTO orderGoodOutDTO = orderGoodOutDTOList.get(i);
            Shop shop = shopMapper.selectByPrimaryKey(orderGoodOutDTO.getShopId());
            List<OrderGoodItem> orderGoodItemList = orderGoodItemMapper.listByOrderId(orderGoodOutDTO.getId());
            orderGoodOutDTO.setOrderGoodItemList(orderGoodItemList);

            if(shop==null) {
                orderGoodOutDTO.setShopname("商圈自营");
            } else {
                orderGoodOutDTO.setShopname(shop.getMerchantName());
            }

            for (int j=0;j<orderGoodItemList.size();j++){
                orderGoodOutDTO.setPrice4(orderGoodItemList.get(j).getPrice4());
                orderGoodOutDTOList.set(i,orderGoodOutDTO);
            }



        }

        return orderGoodOutDTOList;
    }

    @Override
    public List<OrderGoodExcelOutDTO> listMallOrderExcel(MallOrderQueryDTO mallOrderQueryDTO, Page page) throws ParseException {
        OrderGood orderGood = new OrderGood();
        orderGood.setGroupId(mallOrderQueryDTO.getGroupId());
        orderGood.setOrderNo(mallOrderQueryDTO.getOrderNumOrPhone());
        orderGood.setStatus(mallOrderQueryDTO.getStatus());
        orderGood.setShopId(mallOrderQueryDTO.getShopId());

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStart = mallOrderQueryDTO.getDateStart();
        String dateEnd = mallOrderQueryDTO.getDateEnd();
        if(!Tools.isEmpty(dateStart)) {
            Date dateStartDate = dateFormat.parse(dateStart);
            orderGood.setDateStart(dateStartDate);
        }
        if(!Tools.isEmpty(dateEnd)) {
            Date dateEndDate = dateFormat.parse(dateEnd);
            orderGood.setDateEnd(DateUtil.getDateNext(dateEndDate, 1));
        }
//        List<OrderGoodExcelOutDTO> orderGoodExcelOutDTOList = orderGoodMapper.listOrderGoodExcel(orderGood);
//
//
//
//        String orderNo="";
//        Long goodSpecId=null;
//        for(OrderGoodExcelOutDTO orderGoodExcelOutDTO :orderGoodExcelOutDTOList){
//
//            if(orderGoodExcelOutDTO.getGoodSpecId() !=null){
//                orderGoodExcelOutDTO.setSupplyPrice(orderGoodExcelOutDTO.getPrice3()*orderGoodExcelOutDTO.getGoodNum());
//                orderGoodExcelOutDTO.setOriginalPrice(orderGoodExcelOutDTO.getPrice4());
//            }else{
//                orderGoodExcelOutDTO.setSupplyPrice(orderGoodExcelOutDTO.getSupplyPrice()*orderGoodExcelOutDTO.getGoodNum());
//            }
//
//            if(!orderGoodExcelOutDTO.getOrderNo().equals(orderNo)){
//                orderNo=orderGoodExcelOutDTO.getOrderNo();
//                if(orderGoodExcelOutDTO.getGoodSpecId()!=goodSpecId && orderGoodExcelOutDTO.getGoodSpecId()!=null){
//                    goodSpecId =orderGoodExcelOutDTO.getGoodSpecId();
//                }
//            }else{
//                orderGoodExcelOutDTO.setGoodAmount(0);
//                orderGoodExcelOutDTO.setRealAmount(0);
//                orderGoodExcelOutDTO.setBonusCover(0);
//                orderGoodExcelOutDTO.setCouponCover(0);
//                orderGoodExcelOutDTO.setFreightCharge(0);
//
//            }
//        }
        int supplyPrice=0;
        int originalPrice=0;
        String goodName="";
        List<OrderGoodExcelOutDTO> orderGoodExcelOutDTOList = orderGoodMapper.queryOrderGoodExcel(orderGood);
        for(OrderGoodExcelOutDTO orderGoodExcelOutDTO :orderGoodExcelOutDTOList){
            List<OrderGoodExcelOutDTO> orderGoodExcelOutDTOList2 = orderGoodMapper.queryOrderDetail(orderGoodExcelOutDTO.getId());
            if(orderGoodExcelOutDTOList2.size()>1){
                for(OrderGoodExcelOutDTO orderGoodExcelOutDTO2:orderGoodExcelOutDTOList2){
                    goodName +=orderGoodExcelOutDTO2.getGoodName()+";";
                    if(orderGoodExcelOutDTO2.getGoodSpecId() !=null){
                        supplyPrice += orderGoodExcelOutDTO2.getPrice3()*orderGoodExcelOutDTO2.getGoodNum();
                        originalPrice +=orderGoodExcelOutDTO2.getPrice4();
                    }else{
                        supplyPrice +=orderGoodExcelOutDTO2.getSupplyPrice()*orderGoodExcelOutDTO2.getGoodNum();
                    }

                }
                orderGoodExcelOutDTO.setGoodName(goodName.substring(0,goodName.length()-1));
                orderGoodExcelOutDTO.setSupplyPrice(supplyPrice);
                orderGoodExcelOutDTO.setOriginalPrice(originalPrice);
            }else{
                for(OrderGoodExcelOutDTO orderGoodExcelOutDTO2:orderGoodExcelOutDTOList2){
                    if(orderGoodExcelOutDTO2.getGoodSpecId() !=null){
                        orderGoodExcelOutDTO.setSupplyPrice(orderGoodExcelOutDTO2.getPrice3()*orderGoodExcelOutDTO2.getGoodNum());
                        orderGoodExcelOutDTO.setOriginalPrice(orderGoodExcelOutDTO2.getPrice4());
                    }else{
                        orderGoodExcelOutDTO.setSupplyPrice(orderGoodExcelOutDTO2.getSupplyPrice()*orderGoodExcelOutDTO2.getGoodNum());
                    }
                }
            }
        }



        return orderGoodExcelOutDTOList;
    }


   /* @Override
    public BaseOutDTO saveManipulation(MallOrderInDTO mallOrderInDTO,String masterUrl) throws Exception {

        OrderGood orderGood = new OrderGood();
        Date date = new Date();
        PropertyCopyUtil.copyProperties(mallOrderInDTO, orderGood);
        orderGood.setGroupId(mallOrderInDTO.getGroupId());
        orderGood.setGmtModified(date);

        if(mallOrderInDTO.getStatus() != null && mallOrderInDTO.getStatus().equals(BizEnum.MallOrderStatus.WaitingForReceive.getType())){
            orderGood.setDeliverTime(date);
        }

        BaseOutDTO baseOutDTO = new BaseOutDTO();

        OrderGood orderGood1 = orderGoodMapper.selectByPrimaryKey(orderGood.getId());

        //如果是修改收货地址则为用户创建一个已经删除的地址
        if(mallOrderInDTO.getArea() != null) {
            MemberAddress memberAddress = new MemberAddress();
            PropertyCopyUtil.copyPropertiesExclude(mallOrderInDTO, memberAddress, "id");
            memberAddress.setMemberId(orderGood1.getMemberId());
            memberAddress.setIsDefault(false);
            memberAddress.setStatus(0);
            memberAddressMapper.insertSelective(memberAddress);
            orderGood.setAddressId(memberAddress.getId());
        }

        //如果是修改订单号则清空快递详情
        if(mallOrderInDTO.getExpressNo() != null) {
            orderGoodMapper.updateTruncateExpressDetail(orderGood.getId());
        }

        int i = orderGoodMapper.updateByPrimaryKeySelective2(orderGood);
        sqlSessionTemplate.clearCache();

        if(i == 1) {
            //如果是关闭订单
            if(mallOrderInDTO.getStatus() != null && mallOrderInDTO.getStatus() == BizEnum.MallOrderStatus.closed.getType()) {
                //商品加库存
                List<OrderGoodItem> orderGoodItemList = orderGoodItemMapper.listByOrderId(mallOrderInDTO.getId());
                for(int j = 0; j < orderGoodItemList.size(); j++) {
                    mallEntityGoodMapper.addGoodStockNumber(orderGoodItemList.get(j));
                }
                //解锁优惠券
                if(orderGood1.getCouponCover() > 0) {
                    couponUserMapper.updateUnlockCouponOnMember(orderGood1.getOrderNo());
                    couponUserMapper.updateUnlockCouponOnNoMember(orderGood1.getOrderNo());
                }

                //解锁积分
                if(orderGood1.getBonusAmount() > 0) {
                    bonusVerifyLogMapper.updateStatusByOrderId(orderGood1.getId(), ActivityEnum.BonusVerityStatus.OrderCancel.getType());
                    memberMapper.updateMemberBonusUnlock(orderGood1.getMemberId(), orderGood1.getBonusAmount());
                }
            }
            if(mallOrderInDTO.getStatus() != null && mallOrderInDTO.getStatus().equals(BizEnum.MallOrderStatus.WaitingForReceive.getType())){
            	try {
            		//发货通知
            		OrderGood orderGood2 = orderGoodMapper.selectByPrimaryKey(mallOrderInDTO.getId());
    				templateMailSendService.sendOrderTemplate(orderGood2.getOrderNo(), BizEnum.WebTemplateType.template10.getType(), orderGood2.getMemberId(), orderGood.getGroupId(), masterUrl);
    			} catch (Exception e) {
//                    transactionManager.rollback(status);
    				e.printStackTrace();
    			}
            }

            //退款审核通过
            if(mallOrderInDTO.getUserRefund() != null && mallOrderInDTO.getUserRefund() == 3) {
                int realRefundAmount = mallOrderInDTO.getRefundAmount();
                TradeOffline tradeOffline = tradeOfflineMapper.selectByOrderId(orderGood1.getOrderNo());
                if(realRefundAmount > tradeOffline.getRealAmount()) {
//                    transactionManager.rollback(status);
                    return null;
                }
//                saveDoRefund(tradeOffline, realRefundAmount);
                OrderInDTO orderInDTO = new OrderInDTO();
                orderInDTO.setOrderId(mallOrderInDTO.getId());
                orderInDTO.setUserRefund((int)(byte)mallOrderInDTO.getUserRefund());
                orderInDTO.setOrderNo(orderGood1.getOrderNo());
                orderInDTO.setRefundAmount(new BigDecimal(mallOrderInDTO.getRefundAmount()));
                orderInDTO.setGroupId(orderGood1.getGroupId());

                //baseOutDTO= serviceGoodController.ServicegoodConfirmRefund(orderInDTO);
                TradeOfflineBaseOutDTO tradeOfflineOutDTO=orderService.editConfirmRefundServiceGoodOrder(orderInDTO);
                baseOutDTO=orderService.updateRebatewithdraw(tradeOfflineOutDTO.getTradeOffline(), orderInDTO.getRefundAmount());
            }

            baseOutDTO.setErrorCode(Rescode.SUCCESS);
//            transactionManager.commit(status);
        } else {
            baseOutDTO.setErrorCode(Rescode.FAIL);
//            transactionManager.rollback(status);
        }
        return baseOutDTO;
    }

*/


    @Override
    public BaseOutDTO saveManipulation(MallOrderInDTO mallOrderInDTO, String masterUrl) throws Exception {
        OrderGood orderGood = new OrderGood();
        Date date = new Date();
        PropertyCopyUtil.copyProperties(mallOrderInDTO, orderGood);
        orderGood.setGroupId(mallOrderInDTO.getGroupId());
        orderGood.setGmtModified(date);

        if(mallOrderInDTO.getStatus() != null && mallOrderInDTO.getStatus().equals(BizEnum.MallOrderStatus.WaitingForReceive.getType())){
            orderGood.setDeliverTime(date);
        }

        BaseOutDTO baseOutDTO = new BaseOutDTO();

        OrderGood orderGood1 = orderGoodMapper.selectByPrimaryKey(orderGood.getId());
        Shop shop = shopMapper.selectByPrimaryKey(orderGood1.getShopId());

        //如果是修改订单价格和运费 TODO
        if(orderGood1.getStatus() == 1 && mallOrderInDTO.getStatus()==null && mallOrderInDTO.getFreightCharge() != null && mallOrderInDTO.getGoodAmount() != null) {/* mallOrderInDTO.getStatus() == 1*/

            OrderGood orderGood2 = new OrderGood();
            orderGood2.setId(mallOrderInDTO.getId());
            orderGood2.setFreightCharge(mallOrderInDTO.getFreightCharge());
            orderGood2.setGoodAmount(mallOrderInDTO.getGoodAmount());
            orderGoodMapper.updateByPrimaryKeySelective(orderGood2);

        }
        //如果是修改收货地址则为用户创建一个已经删除的地址
        if(mallOrderInDTO.getArea() != null) {
            MemberAddress memberAddress = new MemberAddress();
            PropertyCopyUtil.copyPropertiesExclude(mallOrderInDTO, memberAddress, "id");
            memberAddress.setMemberId(orderGood1.getMemberId());
            memberAddress.setIsDefault(false);
            memberAddress.setStatus(0);
            memberAddressMapper.insertSelective(memberAddress);
            orderGood.setAddressId(memberAddress.getId());
        }

        //如果是修改订单号则清空快递详情
        if(mallOrderInDTO.getExpressNo() != null) {
            orderGoodMapper.updateTruncateExpressDetail(orderGood.getId());
        }

        //如果是关闭订单
        if(mallOrderInDTO.getStatus() != null && mallOrderInDTO.getStatus() == BizEnum.MallOrderStatus.closed.getType()) {
            //修改订单状态为8，关闭订单
            OrderGood orderGoodUpdateStatusParam=new OrderGood();
            orderGoodUpdateStatusParam.setId(mallOrderInDTO.getId());
            orderGoodUpdateStatusParam.setStatus(mallOrderInDTO.getStatus());
            orderGoodMapper.updateByPrimaryKeySelective(orderGoodUpdateStatusParam);

            //商品加库存
            List<OrderGoodItem> orderGoodItemList = orderGoodItemMapper.listByOrderId(mallOrderInDTO.getId());
            for(int j = 0; j < orderGoodItemList.size(); j++) {
                mallEntityGoodMapper.addGoodStockNumber(orderGoodItemList.get(j));
            }
            //解锁优惠券
            if(orderGood1.getCouponCover() > 0) {
                couponUserMapper.updateUnlockCouponOnMember(orderGood1.getOrderNo());
                couponUserMapper.updateUnlockCouponOnNoMember(orderGood1.getOrderNo());
            }

            //解锁积分
            if(orderGood1.getBonusAmount() > 0) {
                bonusVerifyLogMapper.updateStatusByOrderId(orderGood1.getId(), ActivityEnum.BonusVerityStatus.OrderCancel.getType());
                memberMapper.updateMemberBonusUnlock(orderGood1.getMemberId(), orderGood1.getBonusAmount());
            }
        }


        //拒绝退款
        if(mallOrderInDTO.getUserRefund() != null && mallOrderInDTO.getUserRefund() == 2){
            orderGoodMapper.updateByPrimaryKeySelective2(orderGood);
        }

        //发货
        if(mallOrderInDTO.getStatus() !=null && mallOrderInDTO.getStatus()==6){
            List<OrderGoodItem> orderGoodItems= orderGoodItemMapper.selectGoodIdByOrderNo(orderGood1.getOrderNo());//根据订单编号，查到商品ID
            for(OrderGoodItem orderGoodItem:orderGoodItems){
                mallEntityGoodMapper.addSaleNumByGoodID(orderGoodItem.getGoodId(),orderGoodItem.getGoodNum());
            }
            orderGoodMapper.updateByPrimaryKeySelective2(orderGood);
        }

        if(mallOrderInDTO.getStatus() != null && mallOrderInDTO.getStatus().equals(BizEnum.MallOrderStatus.WaitingForReceive.getType())){
            try {
                //发货通知
                OrderGood orderGood2 = orderGoodMapper.selectByPrimaryKey(mallOrderInDTO.getId());
                templateMailSendService.sendOrderTemplate(orderGood2.getOrderNo(), BizEnum.WebTemplateType.template10.getType(), orderGood2.getMemberId(), orderGood.getGroupId(), masterUrl);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //退款审核通过订单是否存在 去退款
        if(mallOrderInDTO.getUserRefund() != null && mallOrderInDTO.getUserRefund() == 3) {
            long shopid = 0L;
            int realRefundAmount = mallOrderInDTO.getRefundAmount();
            TradeOffline tradeOffline = tradeOfflineMapper.selectByOrderId(orderGood1.getOrderNo());
            
            if(tradeOffline==null){
                baseOutDTO.setErrorCode(Rescode.FAIL, "该订单不存在");
                return baseOutDTO;
            }
            if(realRefundAmount > tradeOffline.getRealAmount()) {
//                    transactionManager.rollback(status);
                baseOutDTO.setErrorCode(Rescode.FAIL, "退款金额不能大于实付金额");
                return baseOutDTO;
            }

            OrderInDTO orderInDTO = new OrderInDTO();
            orderInDTO.setOrderId(mallOrderInDTO.getId());
            orderInDTO.setUserRefund((int)(byte)mallOrderInDTO.getUserRefund());
            orderInDTO.setOrderNo(orderGood1.getOrderNo());
            orderInDTO.setRefundAmount(new BigDecimal(mallOrderInDTO.getRefundAmount()));
            orderInDTO.setGroupId(orderGood1.getGroupId());

            if(orderInDTO.getMemberId()!=null&&!tradeOffline.getPayerId().equals(orderInDTO.getMemberId())){
                baseOutDTO.setErrorCode(Rescode.FAIL, "该订单付款信息不一致");
                return baseOutDTO;
            }

            int retreatAmountFee=0;

            if (orderGood1.getOrderNo().startsWith(Const.CONSUMPTION_REAL)) {

                OrderGood orderGood2 = orderGoodMapper.selectByOrderNo(orderGood1.getOrderNo());

//			OrderGood orderGood = orderGoodMapper.selectOrderInfo(orderNo, (byte)1);
                if(orderGood2!= null && orderGood2.getUserRefund()==1){

                }else{
                    baseOutDTO.setErrorCode(Rescode.FAIL, "该订单付款信息不一致");
                    return baseOutDTO;
                }
                retreatAmountFee=orderInDTO.getRefundAmount().intValue();

                if(retreatAmountFee>tradeOffline.getRealAmount()){
                    baseOutDTO.setErrorCode(Rescode.FAIL, "退款金额不能大于实付金额");
                    return baseOutDTO;
                }

                orderGood2.setRefundAmount(retreatAmountFee);
                orderGood2.setUserRefund((byte)3);
                orderGood2.setStatus(BizEnum.MallOrderStatus.Refunded.getType());
                int i =orderGoodMapper.updateByPrimaryKeySelective(orderGood2);

                //如果是待发货状态则增加库存，减销量
                if(orderGood2.getStatus() == BizEnum.MallOrderStatus.WaitingForDeliver.getType()) {
                    List<OrderGoodItem> orderGoodItemList = orderGoodItemMapper.listByOrderId(orderGood2.getId());
                    for(OrderGoodItem orderGoodItem : orderGoodItemList) {
                        mallEntityGoodMapper.reduceGoodStockNumber(orderGoodItem.getId(), -(orderGoodItem.getGoodNum()));
                    }
                }
                shopid = orderGood2.getShopId();

                if(i==1){
                //如果是关闭订单
                if(mallOrderInDTO.getStatus() != null && mallOrderInDTO.getStatus() == BizEnum.MallOrderStatus.closed.getType()) {
                    //修改订单状态为8，关闭订单
                    OrderGood orderGoodUpdateStatusParam=new OrderGood();
                    orderGoodUpdateStatusParam.setId(mallOrderInDTO.getId());
                    orderGoodUpdateStatusParam.setStatus(mallOrderInDTO.getStatus());
                    orderGoodMapper.updateByPrimaryKeySelective(orderGoodUpdateStatusParam);

                    //商品加库存
                    List<OrderGoodItem> orderGoodItemList = orderGoodItemMapper.listByOrderId(mallOrderInDTO.getId());
                    for(int j = 0; j < orderGoodItemList.size(); j++) {
                        mallEntityGoodMapper.addGoodStockNumber(orderGoodItemList.get(j));
                    }
                    //解锁优惠券
                    if(orderGood1.getCouponCover() > 0) {
                        couponUserMapper.updateUnlockCouponOnMember(orderGood1.getOrderNo());
                        couponUserMapper.updateUnlockCouponOnNoMember(orderGood1.getOrderNo());
                    }

                    //解锁积分
                    if(orderGood1.getBonusAmount() > 0) {
                        bonusVerifyLogMapper.updateStatusByOrderId(orderGood1.getId(), ActivityEnum.BonusVerityStatus.OrderCancel.getType());
                        memberMapper.updateMemberBonusUnlock(orderGood1.getMemberId(), orderGood1.getBonusAmount());
                    }
                }
                    if(mallOrderInDTO.getStatus() != null && mallOrderInDTO.getStatus().equals(BizEnum.MallOrderStatus.WaitingForReceive.getType())){
                        try {
                            //发货通知
                            orderGoodMapper.selectByPrimaryKey(mallOrderInDTO.getId());
                            templateMailSendService.sendOrderTemplate(orderGood2.getOrderNo(), BizEnum.WebTemplateType.template10.getType(), orderGood2.getMemberId(), orderGood.getGroupId(), masterUrl);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

                }else{
                    baseOutDTO.setErrorCode(Rescode.FAIL, "该订单不能退款");
                    return baseOutDTO;
                }
                //直接转化成int类型 小于1分钱 不做退款处理
//                if(retreatAmountFee==0){
//                    baseOutDTO.setErrorCode(Rescode.FAIL, "实际可退款金额小于1分钱,无法发起退款");
//                    return baseOutDTO;
//                }
                logger.info ("可退款给用户金额"+retreatAmountFee);


                orderService.updateRebatewithdraw(tradeOffline, orderInDTO.getRefundAmount(),orderGood1.getShopId());
                     Member member=null;
                //判断支付方式  钱包退款 直接返回到钱包
                if(retreatAmountFee !=0){

                    if(tradeOffline.getPayType().equals((byte) BizEnum.PaymentType.Wallet.getType())){
                        member =memberMapper.queryGroup(tradeOffline.getPayerId());
                        PayResult payResult=walletService.updateUserLockedAmount(member.getVirtualCard(),
                                member.getPayGroupCode(), member.getUserId(), retreatAmountFee+"", "0", 0,tradeOffline.getOrderId());
                        tradeOffline.setTransOrderNo(payResult.getOrderId());

                    }else if(tradeOffline.getPayType().equals((byte) BizEnum.PaymentType.WebChat.getType())){

                        TkRefund tkRefund=TkRefund.initialize("WECHAT", tradeOffline.getMerchantNo(), tradeOffline.getOrderId(), retreatAmountFee+"",
                                tradeOffline.getRealAmount()+"", tradeOffline.getTerminalNo());
                        RefundResult payResult=IPayAPI.finishTkRefund(tkRefund);
                        if (!payResult.getResult_code().equals("000000")) {
                            throw new ApplicationException(Rescode.FAIL, "微信调用失败" + payResult.getResult_msg());
                        }
                        tradeOffline.setTransOrderNo(payResult.getRefund_order_no());
                    }
                }

                    tradeOffline.setTransactionStatus((byte) BizEnum.TransactionStatus.ISRefund.getType());
                    tradeOffline.setPayerId(orderGood1.getShopId());
                    tradeOffline.setPayerName(shop.getMerchantName());
                    tradeOffline.setReceiverId(tradeOffline.getPayerId().toString());
                    tradeOffline.setReceiverName(tradeOffline.getPayerName());
                    tradeOfflineMapper.updateByPrimaryKeySelective(tradeOffline);
                    
                    
                    //退款成功 更新会员的消费总额跟消费次数
                    memberMapper.updateMemberUpdateAmount(tradeOffline.getPayerId(),retreatAmountFee);
            		statisMemberMapper.updateMemberCostomerInfo(tradeOffline.getPayerId(),retreatAmountFee);
                    
            		
            		
//                    if(shopid != 0) {//如果是商户商品，则进行推送
                        //获取商户账号
                        Userbase userbase = shopMapper.getUserNameByShopId(shopid);
                        //发送退款推送信息
                        Notice notice = new Notice();
                        try {
                            notice.setNoticetype(0);
                            notice.setSender(tradeOffline.getGroupId());
                            notice.setReceiver(userbase.getUsername());
                            notice.setNoticetitle("您有一笔退款申请");
                            notice.setNoticetarget("ACCOUNT");
                            notice.setNoticebody("您有一笔退款申请");
                            notice.setGroupid(tradeOffline.getGroupId());
                            notice.setNoticestatus(1);
                            notice.setIsplay(0);
                            notice.setType(1);
                            notice.setTvalue("");
                            appNoticeService.sendNoticeToUsers(notice);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
//                    }
                        //微信发送模板消息
                        try {
                            //退款更新会员消费总额 跟次数 升级金额 相应减掉
                            memberService.updateStatisMemberInfo(member.getId(),tradeOffline.getRealAmount());

                            templateMailSendService.sendTemplate(tradeOffline,  BizEnum.WebTemplateType.template5.getType(),
                                    tradeOffline.getPayerId(),
                                    tradeOffline.getGroupId(), BizEnum.PaymentType.WebChat.getType(),masterUrl);
                        } catch (Exception e) {
                            logger.info ("模板消息发送失败"+e);
                        }
                    
                    baseOutDTO.setErrorCode(Rescode.SUCCESS, "退款成功");
                }
		        baseOutDTO.setErrorCode(Rescode.SUCCESS);
		        return baseOutDTO;
            }



    @Override
    public OrderGoodOutDTO get(MallOrderQueryDTO mallOrderQueryDTO) {
        OrderGoodOutDTO orderGoodOutDTO = orderGoodMapper.getByIdAndGroupId(mallOrderQueryDTO.getGroupId(), mallOrderQueryDTO.getId());
        if(orderGoodOutDTO.getExpressDetail() != null) {
            orderGoodOutDTO.setExpressOutDTO(JSON.parseObject(orderGoodOutDTO.getExpressDetail(), ExpressOutDTO.class));
            orderGoodOutDTO.setExpressDetail(null);
        }
        List<OrderGoodItem> orderGoodItemList = orderGoodItemMapper.listByOrderId(orderGoodOutDTO.getId());
        orderGoodOutDTO.setOrderGoodItemList(orderGoodItemList);

        //一单中有多个商品时，供货价需要是供货价乘以数量，
        int supplyPrice=0;
        for(OrderGoodItem orderGoodItem:orderGoodItemList){
            int supplyPriceItem =0;
            //如果有规格ID，就根据规格ID去查找到对应的供货价,否则就从商品表中取到供货价
            if(orderGoodItem.getGoodSpecId()!=null){
                MallEntityGoodSpec mallEntityGoodSpec=mallEntityGoodSpecMapper.selectByPrimaryKey(orderGoodItem.getGoodSpecId());
                //orderGoodOutDTO.setSupplyPrice(mallEntityGoodSpecMapper.selectByPrimaryKey(orderGoodItem.getGoodSpecId()).getPrice3());
                //orderGoodOutDTO.setSupplyPrice(mallEntityGoodSpec.getPrice3()==null?0:mallEntityGoodSpec.getPrice3());
                if(mallEntityGoodSpec!=null){
                    supplyPriceItem = (orderGoodItem.getGoodNum()==null?0:orderGoodItem.getGoodNum())*(mallEntityGoodSpec.getPrice3()==null?0:mallEntityGoodSpec.getPrice3());
                }
            }else{
                MallEntityGood mallEntityGood = mallEntityGoodMapper.selectByPrimaryKey(orderGoodItem.getGoodId());
                if(mallEntityGood !=null){
                    //orderGoodOutDTO.setSupplyPrice(mallEntityGood.getSupplyPrice()==null?0:mallEntityGood.getSupplyPrice());
                    supplyPriceItem=(orderGoodItem.getGoodNum()==null?0:orderGoodItem.getGoodNum())*(mallEntityGood.getSupplyPrice()==null?0:mallEntityGood.getSupplyPrice());
                }
            }
            supplyPrice+=supplyPriceItem;
        }
        orderGoodOutDTO.setSupplyPrice(supplyPrice);
        return orderGoodOutDTO;
    }

    @Override
    public Map<String, Long> orderQuery(Long orderId) {
        Map<String, Long> orderInfo = new HashMap<>();
        if(orderId != null) {
            Map<String, Long> orderNum = orderGoodMapper.selectCountNewOrders(orderId);
            orderInfo.putAll(orderNum);
        } else {
            orderInfo.put("newOrders", 0L);
            long maxOrderId = orderGoodMapper.getMaxOrderId();
            orderInfo.put("maxOrderId", maxOrderId);
        }

        Date date = DateUtil.getDayStart(new Date());
        long todayUnfinished = orderGoodMapper.selectCountTodayOrders(date);
        orderInfo.put("todayUnfinished", todayUnfinished);
        return orderInfo;
    }

    @Override
    public Map<String, Long> selectUserInfoById(Long orderId) {
        return orderGoodMapper.selectUserInfoById(orderId);
    }

    @Override
    public Response getEntityGoodOrderByGoodName(MallOrderQueryDTO mallOrderQueryDTO) throws ParseException {
        List<OrderGoodOutDTO> orderGoodOutDTOList = orderGoodMapper.getOrderByGoodName(mallOrderQueryDTO);
        OrderGoodItem orderGoodItem = new OrderGoodItem();
        if(orderGoodOutDTOList!=null && orderGoodOutDTOList.size()>0){
            for(int i=0;i<orderGoodOutDTOList.size();i++){
                orderGoodItem.setOrderId(orderGoodOutDTOList.get(i).getId());
                List<OrderGoodItem> orderGoodItemList = orderGoodItemMapper.getOrderItemByOrderId(orderGoodItem);
                orderGoodOutDTOList.get(i).setOrderGoodItemList(orderGoodItemList);
            }
            return Response.getSuccess(orderGoodOutDTOList);
        }else{
            return Response.getError("未找到该商品的订单信息");
        }
    }

    private void saveDoRefund(TradeOffline tradeOffline, int realRefundAmount) throws ApplicationException {
        Long groupId;
        String payMerchantCode;
        String payGroupCode;
        Map result = shopGroupRelationMapper.selectShopInfoByShopId(Long.parseLong(tradeOffline.getReceiverId()));
        if(result == null) {
            return;
        } else {
            groupId = (Long) result.get("groupId");
            payGroupCode = groupMapper.selectByPrimaryKey(groupId).getPayGroupCode();
            payMerchantCode = (String) result.get("payMerchantCode");
        }

        Member member = memberMapper.selectByPrimaryKey(tradeOffline.getPayerId());
        Date date = new Date();

        String refundOrderNo =  UtilFun.createOrderNum(Const.CONSUMPTION_REAL);

        TradeOffline tradeOffline1 = new TradeOffline();
        tradeOffline1.setIsWallet(true);
        tradeOffline1.setOrderId(refundOrderNo);
        tradeOffline1.setOldOrderId(tradeOffline.getId());
        tradeOffline1.setGroupId(tradeOffline.getGroupId());
        tradeOffline1.setTransactionType((byte) BizEnum.TransactionType.Refund.getType());
        tradeOffline1.setPayType((byte) 13);
        tradeOffline1.setGmtCreate(date);
        tradeOffline1.setGmtModified(date);
        tradeOffline1.setTransactionStatus((byte) BizEnum.TransactionStatus.Refund.getType());
        tradeOffline1.setOrderAmount(-(tradeOffline.getOrderAmount()));
        tradeOffline1.setRealAmount(-realRefundAmount);
        tradeOffline1.setBonusValue(-(tradeOffline.getBonusValue()));
        tradeOffline1.setBonusAmount(-(tradeOffline.getBonusAmount()));
        tradeOffline1.setPayerId(tradeOffline.getPayerId());
        tradeOffline1.setPayerType(tradeOffline.getPayerType());
        tradeOffline1.setPayerName(tradeOffline.getPayerName());
        tradeOffline1.setReceiverId(tradeOffline.getReceiverId());
        tradeOffline1.setReceiverName(tradeOffline.getReceiverName());

        if(tradeOffline.getPayType() == BizEnum.PaymentType.Wallet.getType()) {

            String orderNo = UtilFun.createOrderNum();
            UnPayConsumption unPayConsumption = UnPayConsumption.initialize(member.getVirtualCard(), payMerchantCode, payGroupCode,
                    realRefundAmount + "", tradeOffline.getTransOrderNo(), orderNo, DateUtils.getDateTimeString("yyyyMMddHHmmss"), AES.AESDncode(Const.AceKey, member.getTradePassword()),
                    UtilFun.createRandomNum(10),156+"");

             posApiServiceTransactional.saveQbRefund(member.getId(), tradeOffline1, unPayConsumption, tradeOffline.getId(), tradeOffline.getBonusAmount(),tradeOffline.getRealAmount());
        } else {

        }

        posApiService.refundBenefit(tradeOffline, refundOrderNo);
    }

    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        this.sqlSessionTemplate = sqlSessionTemplate;
    }
}
